<template>
  <el-card>
    <el-form
      ref="searchForm"
      :inline="true"
      :model="searchFormModel"
      label-width="undefined"
      size="small"
      @submit.prevent>
      <el-form-item :label="'流程编码'" prop="flowCode">
        <el-input
          v-model="searchFormModel.flowCode"
          :disabled="modal_loading"
          :placeholder="$t('forms.pleaseEnter') + '流程编码'"
          @keyup.enter="handleSearch" />
      </el-form-item>
      <el-form-item :label="'流程名称'" prop="flowName">
        <el-input
          v-model="searchFormModel.flowName"
          :disabled="modal_loading"
          :placeholder="$t('forms.pleaseEnter') + '流程名称'"
          @keyup.enter="handleSearch" />
      </el-form-item>
      <el-form-item :label="$t('forms.type')" prop="category">
        <el-input
          v-model="searchFormModel.category"
          :disabled="modal_loading"
          :placeholder="$t('forms.pleaseEnter') + $t('forms.type')"
          @keyup.enter="handleSearch" />
      </el-form-item>
      <el-form-item style="float: right">
        <el-button-group>
          <el-button :loading="modal_loading" type="primary" @click="handleSearch">
            {{ $t('forms.buttons.search') }}
          </el-button>
          <el-button :loading="modal_loading" type="primary" @click="handleSearchReset">
            {{ $t('forms.buttons.reset') }}
          </el-button>
          <el-button :loading="modal_loading" type="primary" @click="handleAdd">
            {{ $t('forms.buttons.add') }}
          </el-button>
        </el-button-group>
        <el-upload
          style="margin-left: 8px"
          action="#"
          :auto-upload="false"
          :show-file-list="false"
          :on-change="handleImport">
          <el-button slot="trigger" type="warning">
            {{ '导入流程' }}
          </el-button>
        </el-upload>
      </el-form-item>
    </el-form>
    <el-table
      ref="table"
      v-loading="modal_loading"
      :data="searchData"
      :default-sort="searchFormModel.orderParam"
      :empty-text="$t('messages.tableNoData')"
      :height="tableHeight"
      border
      header-cell-class-name="query-table-header"
      size="small">
      <el-table-column :label="'流程编码'" prop="flowCode"></el-table-column>
      <el-table-column :label="'流程名称'" prop="flowName"></el-table-column>
      <el-table-column :label="$t('forms.type')" prop="category"></el-table-column>
      <el-table-column
        :label="$t('forms.version')"
        prop="version"
        width="80"
        align="center"></el-table-column>
      <el-table-column :label="'发布状态'" prop="publishStatus" width="100" align="center">
        <template #default="scope">
          <span>{{ selectText(publishStatusList, scope.row.publishStatus) }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="'激活状态'" prop="activityStatus" width="100" align="center">
        <template #default="scope">
          <span>{{ selectText(activityStatusList, scope.row.activityStatus) }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('forms.modifyTime')" prop="updateTime" width="140" align="center">
        <template #default="scope">
          <span>{{ dateTimeFormat(scope.row.updateTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        :fixed="isMobile ? false : 'right'"
        :label="$t('forms.action')"
        align="center"
        prop="action"
        width="90">
        <template #default="scope">
          <el-tooltip :content="$t('forms.buttons.edit')" placement="bottom-end">
            <el-button icon="el-icon-edit" link type="primary" @click="handleEdit(scope.row)" />
          </el-tooltip>
          <el-tooltip :content="$t('forms.buttons.delete')" placement="bottom-end">
            <el-button
              icon="el-icon-delete"
              link
              type="primary"
              @click="handleDeleteRow(scope.row)" />
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      style="margin-top: 5px"
      v-model:current-page="searchFormModel.currPage"
      v-model:page-size="searchFormModel.pageSize"
      :layout="isMobile ? 'prev, pager, next' : 'total, sizes, prev, pager, next, jumper'"
      :page-sizes="searchFormModel.pageSizeArray"
      :size="isMobile ? 'small' : 'default'"
      :total="searchFormModel.totalRows"
      @size-change="handlePageSizeSearch">
    </el-pagination>
    <el-dialog
      v-model="editModal"
      :close-on-click-modal="false"
      :fullscreen="isMobile"
      :title="$t('forms.info')">
      <el-form
        ref="editForm"
        v-loading="modal_loading"
        :model="editFormModel"
        :rules="ruleValidate"
        label-width="auto"
        size="small"
        style="padding-right: 25px"
        @submit.prevent>
        <el-form-item :label="'流程编码:'" prop="flowCode">
          <span v-if="this.action === 1">{{ editFormModel.flowCode }}</span>
          <el-input
            v-else
            v-model="editFormModel.flowCode"
            :disabled="modal_loading"
            :maxlength="40"
            show-word-limit />
        </el-form-item>
        <el-form-item :label="'流程名称:'" prop="flowName">
          <el-input
            v-model="editFormModel.flowName"
            :disabled="modal_loading"
            :maxlength="100"
            show-word-limit />
        </el-form-item>
        <el-form-item :label="$t('forms.type') + ':'" prop="category">
          <el-input
            v-model="editFormModel.category"
            :disabled="modal_loading"
            :maxlength="20"
            show-word-limit />
        </el-form-item>
        <div v-if="action === 1">
          <el-form-item :label="$t('forms.version') + ':'" prop="version">
            <span>{{ editFormModel.version }}</span>
          </el-form-item>
          <el-form-item :label="'发布状态:'" prop="publishStatus">
            <span>{{ selectText(publishStatusList, editFormModel.publishStatus) }}</span>
          </el-form-item>
          <el-form-item :label="'激活状态:'" prop="activityStatus">
            <span>{{ selectText(activityStatusList, editFormModel.activityStatus) }}</span>
          </el-form-item>
          <el-form-item :label="$t('forms.createTime') + ':'" prop="createTime">
            <span>{{ dateTimeFormat(editFormModel.createTime) }}</span>
          </el-form-item>
          <el-form-item :label="$t('forms.modifyTime') + ':'" prop="updateTime">
            <span>{{ dateTimeFormat(editFormModel.updateTime) }}</span>
          </el-form-item>
        </div>
      </el-form>
      <template #footer>
        <div style="text-align: center">
          <el-button-group>
            <el-button
              v-if="action === 1"
              :loading="modal_loading"
              type="success"
              @click="handleEditBpmn">
              {{ '流程设计' }}
            </el-button>
            <el-button
              v-if="action === 1"
              :loading="modal_loading"
              type="info"
              @click="handleDownLoadFile">
              {{ '流程导出' }}
            </el-button>
          </el-button-group>
          <el-button-group v-if="action === 1" style="margin-left: 8px">
            <el-button
              v-if="editFormModel.publishStatus === 0"
              :loading="modal_loading"
              type="success"
              @click="handlePublish(true)">
              {{ '发布' }}
            </el-button>
            <el-button
              v-if="editFormModel.publishStatus === 1"
              :loading="modal_loading"
              type="warning"
              @click="handlePublish(false)">
              {{ '取消发布' }}
            </el-button>
          </el-button-group>
          <el-button-group v-if="action === 1" style="margin-left: 8px">
            <el-button
              v-if="editFormModel.activityStatus === 0"
              :loading="modal_loading"
              type="success"
              @click="handleActivity(true)">
              {{ '激活' }}
            </el-button>
            <el-button
              v-if="editFormModel.activityStatus === 1"
              :loading="modal_loading"
              type="danger"
              @click="handleActivity(false)">
              {{ '挂起' }}
            </el-button>
          </el-button-group>
          <el-button
            :loading="modal_loading"
            type="primary"
            @click="handleSave"
            style="margin-left: 8px">
            {{ $t('forms.buttons.save') }}
          </el-button>
        </div>
      </template>
      <el-dialog v-model="bpmnView" :title="'流程设计'" fullscreen>
        <iframe
          :key="url"
          :src="url"
          :style="{ border: '1px solid #606266', width: '100%', height: bpmnHeight + 'px' }" />
      </el-dialog>
    </el-dialog>
  </el-card>
</template>
<script>
import moment from 'moment'
import { copy, isMobileDevice } from '@/libs/tools'
import { nextTick, ref } from 'vue'
import { useI18n } from 'vue-i18n'
import { useAppStore } from '@/stores/app'

export default {
  name: 'workflowDeploy',
  data() {
    return {
      searchFormModel: {
        flowCode: '',
        flowName: '',
        category: '',
        orderParam: {
          prop: 'createTime',
          order: 'descending'
        },
        currPage: 1,
        totalRows: 0,
        pageSize: 10,
        pageSizeArray: [10, 20, 30, 40]
      },
      editFormModel: {},
      editModal: false,
      modal_loading: false,
      bpmnView: false,
      searchData: [],
      action: 0,
      url: '',
      publishStatusList: [
        { value: 0, label: '未发布' },
        { value: 1, label: '已发布' },
        { value: 9, label: '失效' }
      ],
      activityStatusList: [
        { value: 0, label: '挂起' },
        { value: 1, label: '激活' }
      ]
    }
  },
  computed: {
    isMobile() {
      return isMobileDevice()
    },
    tableHeight() {
      const minHeight = 300
      const height = this.appStore.mainHeight - 80 - 46 - 42 - 4
      if (height < minHeight) {
        return minHeight - 2
      } else {
        return height
      }
    },
    bpmnHeight() {
      return this.appStore.mainHeight + 20
    },
    ruleValidate() {
      return {
        flowCode: [
          {
            required: true,
            message: this.t('forms.processKey') + this.t('forms.notEmpty'),
            trigger: 'blur'
          }
        ],
        flowName: [
          {
            required: true,
            message: this.t('forms.name') + this.t('forms.notEmpty'),
            trigger: 'blur'
          }
        ]
      }
    }
  },
  watch: {
    'searchFormModel.currPage'() {
      this.handleSearch()
    }
  },
  methods: {
    dateTimeFormat(time) {
      return time ? moment(time).format('YYYY-MM-DD HH:mm:ss') : ''
    },
    selectText(list, value) {
      const filter = list.filter((item) => {
        return item.value === value
      })
      if (filter.length > 0) {
        return filter[0].label
      } else {
        return ''
      }
    },
    handleAdd() {
      this.editModal = true
      this.action = 0
      this.editFormModel = {}
    },
    handleDelete(rowIds) {
      this.modal_loading = true
      this.$api.request.workFlowDeploy
        .delete(rowIds)
        .then((res) => {
          this.modal_loading = false
          if (res) {
            this.$message.success(this.t('messages.deleteSuccess') + '')
            this.handleSearch()
          }
        })
        .catch(() => {
          this.modal_loading = false
        })
    },
    handleSave(callBackFunc) {
      this.editForm.validate((valid) => {
        if (valid) {
          this.modal_loading = true
          switch (this.action) {
            case 0:
              this.$api.request.workFlowDeploy
                .create({
                  flowCode: this.editFormModel.flowCode,
                  flowName: this.editFormModel.flowName,
                  category: this.editFormModel.category
                })
                .then((res) => {
                  this.modal_loading = false
                  if (res) {
                    if (typeof callBackFunc === 'function') {
                      callBackFunc()
                    } else {
                      this.$message.success(this.t('messages.saveSuccess') + '')
                      this.editModal = false
                      this.handleSearch()
                    }
                  }
                })
                .catch(() => {
                  this.modal_loading = false
                })
              break
            case 1:
              this.modal_loading = true
              this.$api.request.workFlowDeploy
                .update({
                  id: this.editFormModel.id,
                  flowCode: this.editFormModel.flowCode,
                  flowName: this.editFormModel.flowName,
                  category: this.editFormModel.category
                })
                .then((res) => {
                  this.modal_loading = false
                  if (res) {
                    if (typeof callBackFunc === 'function') {
                      callBackFunc()
                    } else {
                      this.$message.success(this.t('messages.saveSuccess') + '')
                      this.editModal = false
                      this.handleSearch()
                    }
                  }
                })
                .catch(() => {
                  this.modal_loading = false
                })
              break
          }
        }
      })
    },
    handlePublish(publish) {
      if (publish) {
        this.$confirm(
          `确定发布流程【${this.editFormModel.flowCode}】【${this.editFormModel.flowName}】？`,
          this.t('dialog.confirm') + '',
          {
            type: 'warning'
          }
        )
          .then(() => {
            this.handleSave(() => {
              this.modal_loading = true
              this.$api.request.workFlowDeploy
                .publish(this.editFormModel.id)
                .then((res) => {
                  this.modal_loading = false
                  if (res) {
                    this.$message.success(res.data.message)
                    this.editModal = false
                    this.handleSearch()
                  }
                })
                .catch(() => {
                  this.modal_loading = false
                })
            })
          })
          .catch(() => {})
      } else {
        this.$confirm(
          `确定取消发布流程【${this.editFormModel.flowCode}】【${this.editFormModel.flowName}】？`,
          this.t('dialog.confirm') + '',
          {
            type: 'warning'
          }
        )
          .then(() => {
            this.handleSave(() => {
              this.modal_loading = true
              this.$api.request.workFlowDeploy
                .unPublish(this.editFormModel.id)
                .then((res) => {
                  this.modal_loading = false
                  if (res) {
                    this.$message.success(res.data.message)
                    this.editModal = false
                    this.handleSearch()
                  }
                })
                .catch(() => {
                  this.modal_loading = false
                })
            })
          })
          .catch(() => {})
      }
    },
    handleActivity(activity) {
      if (activity) {
        this.$confirm(
          `确定激活流程【${this.editFormModel.flowCode}】【${this.editFormModel.flowName}】？`,
          this.t('dialog.confirm') + '',
          {
            type: 'warning'
          }
        )
          .then(() => {
            this.modal_loading = true
            this.$api.request.workFlowDeploy
              .active(this.editFormModel.id)
              .then((res) => {
                this.modal_loading = false
                if (res) {
                  this.$message.success(res.data.message)
                  this.editModal = false
                  this.handleSearch()
                }
              })
              .catch(() => {
                this.modal_loading = false
              })
          })
          .catch(() => {})
      } else {
        this.$confirm(
          `确定挂起流程【${this.editFormModel.flowCode}】【${this.editFormModel.flowName}】？`,
          this.t('dialog.confirm') + '',
          {
            type: 'warning'
          }
        )
          .then(() => {
            this.modal_loading = true
            this.$api.request.workFlowDeploy
              .unActive(this.editFormModel.id)
              .then((res) => {
                this.modal_loading = false
                if (res) {
                  this.$message.success(res.data.message)
                  this.editModal = false
                  this.handleSearch()
                }
              })
              .catch(() => {
                this.modal_loading = false
              })
          })
          .catch(() => {})
      }
    },
    handlePageSizeSearch(size) {
      this.searchFormModel.pageSize = size
      this.handleSearch()
    },
    handleSearch() {
      let searchParam = {
        flowCode: this.searchFormModel.flowCode,
        flowName: this.searchFormModel.flowName,
        category: this.searchFormModel.category,
        queryParam: {
          currPage: this.searchFormModel.currPage,
          pageSize: this.searchFormModel.pageSize
        }
      }
      if (this.searchFormModel.orderParam.order !== 'normal') {
        searchParam.queryParam.orderName = this.searchFormModel.orderParam.prop
        searchParam.queryParam.orderCommand = this.searchFormModel.orderParam.order
      }
      this.modal_loading = true
      this.$api.request.workFlowDeploy
        .query(searchParam)
        .then((res) => {
          this.modal_loading = false
          if (res) {
            this.searchFormModel.totalRows = res.data.totalElements
            this.searchData = []
            this.searchData = res.data.content
          }
        })
        .catch(() => {
          this.searchData = []
          this.modal_loading = false
        })
    },
    handleSearchReset() {
      this.searchForm.resetFields()
    },
    handleDeleteRow(row) {
      this.$confirm(this.t('messages.deleteDataConfirm') + '', this.t('dialog.confirm') + '', {
        type: 'warning'
      })
        .then(() => {
          this.handleDelete([row.id])
        })
        .catch(() => {})
    },
    handleEdit(row) {
      this.editModal = true
      this.action = 1
      this.editFormModel = copy(row)
    },
    handleEditBpmn() {
      this.bpmnView = true
      nextTick(() => {
        if (this.editFormModel.id && this.editFormModel.id !== '') {
          this.url =
            this.appStore.appInfo.baseURL +
            `/warm-flow-ui/index.html?id=${this.editFormModel.id}&disabled=false`
          window.onmessage = (event) => {
            switch (event.data.method) {
              case 'close':
                this.bpmnView = false
                this.handleSearch()
                break
            }
          }
        }
      })
    },
    handleDownLoadFile() {
      this.$api.request.workFlowDeploy.downLoadFile(this.editFormModel.id)
    },
    handleImport(file) {
      this.$api.getFileContent(file).then((res) => {
        if (res) {
          this.modal_loading = true
          let content = ''
          if (typeof res.data !== 'string') {
            content = JSON.stringify(res.data)
          } else {
            content = res.data
          }
          this.$api.request.workFlowDeploy
            .import({ content: content })
            .then((res) => {
              this.modal_loading = false
              if (res) {
                this.$message.success(res.data.message)
                this.handleSearch()
              }
            })
            .catch(() => {
              this.modal_loading = false
            })
        }
      })
    }
  },
  mounted() {
    this.handleSearch()
  },
  activated() {
    nextTick(() => {
      this.table.doLayout()
    })
  },
  setup() {
    const searchForm = ref(null)
    const table = ref(null)
    const editForm = ref(null)
    const { t } = useI18n()
    const appStore = useAppStore()
    return { searchForm, table, editForm, t, appStore }
  }
}
</script>
